<template>
  <el-dialog title="清机维护" append-to-body width="700px" :model-value="modelValue" @close="commEvent.onClose" :z-index="2000">
    <el-form ref="formRef" label-suffix="：">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="厂区"> {{ factorys.find(item => item.value === props.rows?.factoryId)?.label }} </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产线">
            {{ lines.find(item => item.value === props.rows?.lineId)?.label }}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="生产订单"> {{ props.rows?.orderCode }}</el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="清机记录">
            <div class="clean-records">
              <div class="table-header">
                <el-button type="primary" size="small" @click="commEvent.addCleanRecord">新增</el-button>
              </div>
              <el-table :data="cleanRecords" border :style="{ width: '100%' }" size="small">
                <el-table-column label="清机等级" width="150">
                  <template #default="{ row }">
                    <el-select v-model="row.cleanLevel" placeholder="请选择" size="small" filterable>
                      <el-option
                        v-for="item in cleanLevelOptions"
                        :key="String(item.value)"
                        :label="String(item.label)"
                        :value="String(item.value)"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="次数" width="120">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.cleanCnt"
                      :min="1"
                      :precision="0"
                      controls-position="right"
                      size="small"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="总时长" width="120">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.cleanTimes"
                      :min="0"
                      :precision="1"
                      controls-position="right"
                      size="small"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ $index }">
                    <el-button type="danger" size="small" link @click="commEvent.deleteCleanRecord($index)"> 删除 </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="commEvent.onClose">取消</el-button>
        <el-button type="primary" @click="commEvent.onEnter">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { PropType, ref, watch } from "vue"
import { FormInstance, ElMessage } from "element-plus"
import { EnumProps } from "@/components/ProTable/interface"
import { SystemSpace } from "@/api/interface/order"
import { cleanList, saveCleanRecords } from "@/api/modules/order"
import { useUserStore } from "@/stores/modules/user"
// 清机记录类型定义
interface CleanRecord {
  id?: number
  cleanLevel: string
  cleanCnt: number
  cleanTimes: number
  personCharge?: string
}

const props = defineProps({
  modelValue: Boolean,
  rows: { type: Object as PropType<SystemSpace.dailyList>, default: () => {} },
  factorys: { type: Array as PropType<EnumProps[]>, default: () => [] },
  lines: { type: Array as PropType<EnumProps[]>, default: () => [] }
})
const emit = defineEmits(["update:modelValue", "refresh"])

// 参数
const formRef = ref<FormInstance>() // 表单实例
const cleanRecords = ref<CleanRecord[]>([]) // 清机记录数据
const userStore = useUserStore() // 用户信息

// 清机等级选项
const cleanLevelOptions = ref<EnumProps[]>([
  { label: "A", value: "A" },
  { label: "B", value: "B" },
  { label: "C", value: "C" }
])
// 事件集合
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 确定
  onEnter: async () => {
    if (!props.rows?.id) {
      ElMessage.error("缺少日产数据ID")
      return
    }

    try {
      // 验证清机记录数据
      const invalidRecords = cleanRecords.value.filter(
        record => !record.cleanLevel || record.cleanCnt <= 0 || record.cleanTimes < 0
      )

      if (invalidRecords.length > 0) {
        ElMessage.warning("请完善清机记录信息")
        return
      }

      // 准备保存数据
      const saveData = {
        dailyId: props.rows.id,
        cleanList: cleanRecords.value.map(record => ({
          id: record.id || undefined,
          cleanLevel: record.cleanLevel,
          cleanCnt: record.cleanCnt,
          cleanTimes: record.cleanTimes,
          personCharge: record.personCharge || userStore.userInfo.name
        }))
      }

      console.log("保存清机记录：", saveData)
      const { code } = await saveCleanRecords(saveData)

      if (code === "200") {
        ElMessage.success("保存成功")
        emit("refresh")
        commEvent.onClose()
      } else {
        ElMessage.error("保存失败")
      }
    } catch (error) {
      console.error("保存清机记录失败：", error)
      ElMessage.error("保存失败，请重试")
    }
  },
  // 新增清机记录
  addCleanRecord: () => {
    cleanRecords.value.push({
      cleanLevel: "",
      cleanCnt: 1,
      cleanTimes: 0,
      personCharge: userStore.userInfo.name
    })
  },
  // 删除清机记录
  deleteCleanRecord: (index: number) => {
    cleanRecords.value.splice(index, 1)
  }
}
watch(
  () => props.modelValue,
  async val => {
    console.log("EditDailyDialog modelValue 变化：", val)
    if (val) {
      if (props.rows.id) {
        const { data } = await cleanList(props.rows.id)
        console.log("获取清机记录：", data)
        cleanRecords.value = data.map(item => ({
          id: item.id,
          cleanLevel: item.cleanLevel,
          cleanCnt: item.cleanCnt,
          cleanTimes: item.cleanTimes,
          personCharge: item.personCharge || userStore.userInfo.name
        }))
      }
    }
  }
)
</script>

<style lang="scss" scoped>
:deep(.el-select-dropdown) {
  z-index: 999999 !important; /* 提升 select 下拉框层级 */
}
.clean-records {
  .table-header {
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-table) {
    .el-table__cell {
      padding: 8px 0;
    }
  }

  :deep(.el-input-number) {
    .el-input__wrapper {
      padding-left: 8px;
      padding-right: 8px;
    }
  }

  :deep(.el-select) {
    .el-input__wrapper {
      padding-left: 8px;
      padding-right: 8px;
    }
  }
}
</style>
